package server

import (
	"context"
	"github.com/go-co-op/gocron"
	"go.uber.org/zap"
	"onvif_server/internal/service"
	"time"
)

type Config struct {
	CheckCameraInterval     time.Duration `help:"检查摄像头是否在线间隔时间,设置为0将永远不会执行" default:"30s"`
	UpdateCoverImgInterval  time.Duration `help:"更新摄像头封面间隔时间,设置为0将永远不会执行" default:"60s" devDefault:"0" testDefault:"60s"`
	AutoHandleMediaInterval time.Duration `help:"定期设置ZL流媒体服务,设置为0将永远不会执行" default:"60s" devDefault:"0" testDefault:"60s"`
	AlarmCleanupAt          string        `help:"告警信息清理时间，格式[hh:mm],设置为空将永远不会执行" default:"01:30"`
}

type Task struct {
	log           *zap.Logger
	loc           *time.Location
	config        *Config
	scheduler     *gocron.Scheduler
	cameraService service.CameraService
	alarmService  service.AlarmService
}

func NewTask(log *zap.Logger, conf *Config, loc *time.Location, cameraService service.CameraService, alarmService service.AlarmService) *Task {
	return &Task{
		log:           log.Named("task"),
		config:        conf,
		loc:           loc,
		cameraService: cameraService,
		alarmService:  alarmService,
	}
}
func (t *Task) Start(ctx context.Context) error {
	// eg: crontab task
	t.scheduler = gocron.NewScheduler(t.loc)

	var err error
	//每隔一分钟检测摄像头
	if t.config.CheckCameraInterval > 0 {
		_, err = t.scheduler.Every(int(t.config.CheckCameraInterval/time.Second)).Seconds().Do(t.cameraService.CheckCameraOnline, ctx)
		if err != nil {
			t.log.Error("CheckCameraOnline error", zap.Error(err))
		}
	}
	//30s 设置一次摄像头封面
	if t.config.UpdateCoverImgInterval > 0 {
		_, err = t.scheduler.Every(int(t.config.UpdateCoverImgInterval/time.Second)).Seconds().Do(t.cameraService.UpdateCameraCoverImg, ctx)
		if err != nil {
			t.log.Error("UpdateCameraCoverImg error", zap.Error(err))
		}
	}

	//30s 定期设置ZL流媒体服务
	if t.config.AutoHandleMediaInterval > 0 {
		_, err = t.scheduler.Every(int(t.config.AutoHandleMediaInterval/time.Second)).Seconds().Do(t.cameraService.AutoHandleMedia, ctx)
		if err != nil {
			t.log.Error("AutoHandleMedia error", zap.Error(err))
		}
	}
	//每天清理预警数据
	if t.config.AlarmCleanupAt != "" {
		_, err = t.scheduler.Every(1).Day().At(t.config.AlarmCleanupAt).Do(t.alarmService.TaskDayCleaning, ctx)
		if err != nil {
			t.log.Error("DayCleaning error", zap.Error(err))
		}
	}
	t.scheduler.StartAsync()
	t.log.Info("Task start...")
	return nil
}
func (t *Task) Stop(ctx context.Context) error {
	t.scheduler.Stop()
	t.log.Info("Task stop...")
	return nil
}
